<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/4/25
 * Time: 16:11
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\api\controller\v1;

use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\CouponCoupon;
use app\common\model\CouponReceive;
use Htlove\Time;
use think\App;
use think\facade\Log;

class Coupon extends Base
{
    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new CouponCoupon();
    }

    /**
     * @return array|\think\response\Json
     */
    public function getCouponByListInfo()
    {
        //查询优惠券
        try {
            $row = $this->model->getCouponByUserList($this->m_openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "ok", $row);
    }

    /**
     * @return array|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function receiveCouponById()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id == 0) {
            return Show::json_show(Status::status_error, "内部异常");
        }
        //查询id

        $row = $this->model->getBaseById($id);
        if (!$row) {
            return Show::json_show(Status::mini_error, "记录不存在");
        }
        if ($row['status'] != 1) {
            return Show::json_show(Status::mini_error, "优惠券不存在");
        }
        if ($row['start_time'] > time() || $row['end_time'] < time()) {
            return Show::json_show(Status::mini_error, "不在领取时间范围内");
        }
        if ($row['push'] != 1) {
            return Show::json_show(Status::mini_error, "暂时不能领取");
        }

        $coupon_receive = new CouponReceive();
        $openid = $this->m_openid;
        if ($row['new_limit'] == 1) {  //新人判断规则是 只要没有领过的都是新人
            $count = $coupon_receive->getUserCouponReceiveByCount($openid);
            if ($count['count'] != 0) {
                return Show::json_show(Status::mini_error, "新用户才能领取");
            }
        }
        //每人每天限制领取
        if ($row['receive_day_limit']) {
            //查询今日领取的次数
            $where = [
                ["openid", '=', $openid],
                ["coupon_id", '=', $row['id']],
                ['create_time', 'between', Time::instance()->today()]
            ];
            $count = $coupon_receive->getUserCouponReceiveIdByCount($where, "count(*) as count");
            if ($count['count'] >= $row['receive_day_limit']) {
                //已超过领取次数
                return Show::json_show(Status::mini_error, "一天只能领{$row['receive_day_limit']}张");
            }
        }
        //每人可以领取
        if ($row['receive_limit'] != 0) { //每人限制领取限制
            //查询领取限制
            $count = $coupon_receive->getUserCouponReceiveIdByCount([
                "openid" => $openid,
                "coupon_id" => $row['id']
            ], "count(*) as count");
            if ($count['count'] >= $row['receive_limit']) {
                return Show::json_show(Status::mini_error, "只能领取{$row['receive_limit']}张");
            }
        }
        //直接领取
        $end_time = 0;
        if ($row['use_time_type'] == 1) {
            $end_time = $row['use_end_time'];
        } else {
            $end_time = time() + $row['use_days'] * 86400;
        }
        $insert_data = [
            "coupon_id" => $row['id'],
            "openid" => $openid,
            "end_time" => $end_time
        ];
        $this->model->startTrans();
        try {
            $coupon_receive->save($insert_data);
            $this->model->where('id', $row['id'])->dec('surplus_count')->update();
            $this->model->commit();
        } catch (\Exception $e) {
            Log::error("接口领取优惠券:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            $this->model->rollback();
            return Show::json_show(Status::mini_error, "领取失败");
        }
        return Show::json_show(Status::mini_normal, "领取成功");
    }

    /**
     * @return array|\think\response\Json
     */
    public function getUserCouponByListInfo()
    {
        $page = $this->request->param('page', 1, 'intval');
        $limit = $this->request->param('limit', 10, 'intval');
        try {
            $row = (new CouponReceive())->getBaseByListPage([
                ["openid", '=', $this->m_openid],
                ["status", '=', 0],
                ['end_time', '>', time()]
            ], $page, $limit, '*', "id desc", 'coupon');
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "查询失败");
        }
        return Show::json_show(Status::mini_normal, 'OK', $row);

    }

}